<template>
  <el-form :model="detailForm" ref="detailForm" :label-position="labelPosition">
    <el-card class="box-card" shadow="never">
      <div slot="header">
        <span>保险变更信息</span>
      </div>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="保险变更日期：" style="width: 70%" prop="changeTime"
                        :rules="{required:state==='write',message: '请选择保险变更日期',target:'blur'}">
            <el-date-picker v-if="isEdit" v-model="detailForm.changeTime" type="date" placeholder="请选择保险变更日期"
                            value-format='yyyy-MM-dd' style="width: 100%;">
            </el-date-picker>
            <span v-else></span>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col>
          <el-table size="mini" :data="detailForm.changeList" border style="width: 100%"
                    :header-cell-class-name="headerClass">
            <el-table-column align="center" label="操作" width="68" v-if="isEdit" fixed="left">
              <template #default="{row,$index}">
                <el-button size="mini" type="text" @click="delThreeLoss(row, $index)">删除</el-button>
              </template>
            </el-table-column>

            <el-table-column align="center" label="保险险种" prop="payee">
              <template #default="{row,$index}">
                <el-form-item class="formTable" :prop="`changeList.${$index}.insuranceProCode`"
                              :rules="{type:'number', required:true,message: '请选择保险险种',target:'change'}">
                  <el-select v-model="row.insuranceProCode" v-if="isEdit" @change="handleChange(row,$index)"
                             style="width: 100%" placeholder="请选择保险险种">
                    <el-option v-for="item in detailForm.insuranceVo.businessList" :key="item.insuranceProCode"
                               :label="item.insuranceProName" :value="item.insuranceProCode">
                    </el-option>
                  </el-select>
                  <span v-else>
                    {{ row.insuranceProCode }}
                  </span>
                </el-form-item>
              </template>
            </el-table-column>

            <el-table-column align="center" label="变更前保额/万元" prop="beforeChange">
              <template #default="{row,$index}">
                <!--@change=" changeThreeLoss(row, $index, 'beforeChange')"-->
                <el-form-item class="formTable" :prop="'changeList.'+$index+'.beforeChange'"
                              :rules="{required:state==='write',target:'blur'}">
                  <el-input v-model="row.beforeChange" v-if="isEdit"/>
                  <span v-else>
                    <span v-if="handleReg(row.beforeChange)">
                      {{ format_thousand(row.beforeChange) }}
                    </span>
                    <span v-else>
                      {{ row.beforeChange }}
                    </span>
                  </span>
                </el-form-item>
              </template>
            </el-table-column>

            <el-table-column align="center" label="变更后保额/万元" prop="afterChange">
              <template #default="{row,$index}">
                <el-form-item class="formTable" :prop="'changeList.'+$index+'.afterChange'"
                              :rules="{required:state==='write',target:'blur'}">
                  <el-input v-model="row.afterChange" v-if=" isEdit"
                            @change="changeAfterChange(row, $index, 'afterChange')" size="mini"/>
                  <span v-else>
                    {{ row.afterChange }}
                  </span>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column align="center" label="保险费用" prop="insurancePrice">
              <template #default="{row,$index}">
                <el-form-item class="formTable" :prop="'changeList.'+$index+'.insurancePrice'"
                              :rules="{required:state==='write',target:'blur'}">
                  <el-input v-model="row.insurancePrice" v-if=" isEdit" v-thousand
                            @change="changeThreeLoss(row, $index, 'insurancePrice')" size="mini"/>
                  <span v-else>
                    {{ format_thousand(row.insurancePrice) }}
                  </span>
                </el-form-item>
              </template>
            </el-table-column>
            <template v-slot:append
                      v-if="isEdit && !(detailForm.changeList.length === detailForm.insuranceVo.businessList.length)">
              <div class="flex-xy-center" style="height: 30px">
                <e-button type="text" icon="eel-icon-plus" @click="addDecoration">添加
                </e-button>
              </div>
            </template>
          </el-table>
        </el-col>
      </el-row>

    </el-card>
  </el-form>
</template>

<script>
import {getInsuranceBusinessQuota} from "@/api/bxgl/insureManageApi.js";

export default {
  name: "alterInsurance", //保险变更信息
  props: {
    value: {
      type: Object,
      default: {},
    },
    state: {
      type: String,
      default: "",
    },
  },
  computed: {
    detailForm: {
      get() {
        let that = this;
        const proxy = new Proxy(that.value, {
          get(target, key, value) {
            return Reflect.get(target, key);
          },
          set(target, key, value) {
            that.$emit("input", {...target, [key]: value});
            return true;
          },
        });
        return proxy;
      },
    },
    labelPosition() {
      if (this.isEdit) {
        return "top";
      } else {
        return "right";
      }
    },
    isEdit() {
      let bool;
      switch (this.state) {
        case "write":
          bool = true;
          break;
        case "disabled":
          bool = false;
          break;
        case "readonly":
          bool = false;
          break;
      }
      return bool;
    },
    handleReg() {
      return function (val) {
        var pattern = new RegExp("[0-9]+");
        if (pattern.test(val)) {
          return true;
        } else {
          return false;
        }
      };
    },
  },
  watch: {},
  data() {
    return {
      headerClassList: [
        "payee",
        "beforeChange",
        "afterChange",
        "insurancePrice",
      ],
    };
  },
  created() {
  },
  mounted() {
  },
  methods: {
    headerClass({row, column, rowIndex, columnIndex}) {
      for (let i = 0; i < row.length; i++) {
        if (
            this.headerClassList.includes(row[i].property) &&
            i === columnIndex &&
            this.isEdit
        ) {
          return "header-class";
        }
      }
    },

    addDecoration: function () {
      let obj = {
        insuranceProName: "",
        insuranceProCode: null,
        beforeChange: "",
        afterChange: "",
        insurancePrice: "",
      };
      this.value.changeList.push(obj);
    },

    handleChange(row, index) {
      row.insuranceProName = this.value.insuranceVo.businessList
          .map((a) => {
            if (a.insuranceProCode === row.insuranceProCode) {
              return a.insuranceProName;
            }
          })
          .filter((a) => a)[0];
      for (let i = 0; i < this.value.changeList.length; i++) {
        let code = this.value.changeList[i].insuranceProCode;
        if (index !== i && code === row.insuranceProCode) {
          this.$message({
            type: "warning",
            message: "保险险种已存在",
          });
          row.insuranceProCode = "";
          row.insuranceProName = "";
        }
      }
      if (row.insuranceProCode) {
        let obj = {
          insuranceId: this.value.insuranceVo.syxId,
          typeKey: row.insuranceProCode,
        };
        getInsuranceBusinessQuota(obj).then((res) => {
          row.beforeChange = res.msg;
        });
      }
    },

    changeAfterChange(row, key, field) {
      let msg = /^(?:[1-9]\d*|0)(?:\.\d+)?$/;
      if (row[field]) {
        if (this.handleReg(this.value.changeList[key].beforeChange)) {
          if (msg.test(Number(row[field]))) {
            if (Number(row[field]) >= 0) {
              let _value = row[field].toString().match(/^\d+(?:\.\d{0,2})?/)[0];
              row[field] = _value;
            } else {
              row[field] = "";
            }
          } else {
            row[field] = "";
          }
        } else {
          row[field] =  row[field]
        }
      }
    },

    changeThreeLoss(row, key, field) {
      let msg = /^(?:[1-9]\d*|0)(?:\.\d+)?$/;
      // if (field == "price") {
      if (row[field]) {
        if (msg.test(Number(row[field]))) {
          if (Number(row[field]) >= 0) {
            let _value = row[field].toString().match(/^\d+(?:\.\d{0,2})?/)[0];
            row[field] = _value;
          } else {
            row[field] = "";
          }
        } else {
          row[field] = "";
        }
      }
    },

    delThreeLoss(row, key) {
      this.detailForm.changeList.splice(key, 1);
    },

    handleEffect() {
      return new Promise((resolve, reject) => {
        this.$refs.detailForm.validate((valid) => {
          if (valid) {
            resolve();
          } else {
            this.locateToErr();
            reject();
          }
        });
      });
    },

    locateToErr() {
      this.$nextTick(() => {
        let isError = document.getElementsByClassName("is-error");
        isError[0].scrollIntoView({
          // 滚动到指定节点
          // 值有start,center,end，nearest，当前显示在视图区域中间
          block: "center",
          // 值有auto、instant,smooth，缓动动画（当前是慢速的）
          behavior: "smooth",
        });
      });
    },

    valid() {
      return new Promise((resolve, reject) => {
        this.$refs.detailForm.validate((valid) => {
          resolve(valid);
        });
      });
    },
  },
};
</script>

<style scoped lang="scss">
.box-card {
  margin-bottom: 20px;
}

::v-deep.formTable {
  margin-bottom: 0;
}

::v-deep .header-class {
  .cell::before {
    content: "*";
    color: red;
    padding-right: 2px;
    font-size: 14px;
  }
}
</style>


